<!--
  -   合同管理.   :permission="permissionList"
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :table-loading="tableLoading"
        :search.sync="searchForm"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-del="handleDelete"
        @search-reset="searchReset"
      >
        <template slot-scope="scope" slot="signDateSearch">
          <!-- <el-input
            placeholder="自定义输入框"
            v-model="search.signDate"
          ></el-input> -->
          <el-date-picker
            v-model="search.signDate"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :picker-options="pickerOptions0"
          >
          </el-date-picker>
        </template>
        <template slot="menuLeft" slot-scope="scope">
          <el-button
            v-if="contract_ctproject_add"
            class="filter-item"
            type="primary"
            icon="el-icon-plus"
            @click="addOrUpdateHandle('add', '')"
          >
            新增
          </el-button>
          <el-button
            v-if="contract_ctproject_export"
            class="filter-item"
            type="default"
            icon="el-icon-download"
            @click="rmEexport()"
          >
            导出
          </el-button>
          <el-button
            v-if="contract_ctproject_import"
            class="filter-item"
            type="default"
            icon="el-icon-upload2"
            @click="rmImport()"
          >
            导入
          </el-button>
          <!-- <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane
              v-for="(item,index) in tabOptions"
              :label="item.label"
              :name="item.value"
              :key="index"
            ></el-tab-pane>
          </el-tabs> -->
        </template>

        <template slot="contractNumber" slot-scope="scope">
          <el-link
            type="primary"
            :underline="false"
            @click="handleView('view', scope.row)"
            >{{ scope.row.contractNumber }}</el-link
          >
        </template>

        <template slot="companyName" slot-scope="scope">
          <span>{{
            scope.row.company != null ? scope.row.company.name : ''
          }}</span>
        </template>
        <!-- <template
          slot="companyName"
          slot-scope="scope"
        >
          <span>{{scope.row.company!=null?scope.row.company.name:''}}</span>
        </template> -->
        <template slot="projectName" slot-scope="scope">
          <span
            v-bind:key="item.rmProject.projectId"
            v-for="item in scope.row.ctContractProjectList"
            >{{ item.rmProject.projectName }}</span
          >
        </template>
        <template slot="ctContractProject" slot-scope="scope">
          <!-- scope.row.projectIds.split(',') -->
          <template
            v-for="(item, index) in scope.row.projectIds
              ? scope.row.projectIds.split(',')
              : []"
          >
            <span v-if="index >= 1" :key="index + ','">,</span>

            <el-link
              type="primary"
              :underline="false"
              :key="index"
              @click="handleViewEstate('view', item)"
              >{{
                item | getCtContractProject(scope.row.ctContractProject, index)
              }}
            </el-link>
          </template>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            v-if="contract_ctproject_get"
            type="text"
            @click="handleView('view', scope.row)"
          >
            查看
          </el-button>
          <el-button
            v-if="contract_ctproject_edit && activeName == 0"
            type="text"
            @click="addOrUpdateHandle('edit', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-if="contract_ctproject_del && activeName == 0"
            type="text"
            @click="handleDelete(scope.row, scope.index)"
          >
            删除
          </el-button>
          <!-- <el-button
            v-if="generator_ctcontractchargesummary_get && scope.row.contractTypeId == 1 && scope.row.contractStatus == 1"
            type="text"
            @click="updatePrice(scope.row.contractNumber,scope.row.id)"
          >
            修改合同单价
          </el-button> -->
        </template>
      </avue-crud>

      <table-form
        v-if="addOrUpdateVisible"
        ref="addOrUpdate"
        @refreshDataList="getList"
      ></table-form>

      <table-forms
        v-if="viewVisible"
        ref="viewBtn"
        @refreshDataList="getList"
        @openxuqian="openxuqian"
      ></table-forms>
      <!--<table-form v-if="viewVisible" ref="viewBtn" @refreshDataList="getList"></table-form>-->
    </basic-container>
    <!--导入-->
    <el-dialog
      title="批量导入"
      :visible.sync="uploadlg.show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
      :before-close="BeforeClose"
    >
      下载模板：<el-button
        type="text"
        size="mini"
        style="color: #409eff"
        @click="onDowmload"
        >合同导入模板.xlsx</el-button
      >

      <br />
      <br />
      <el-upload
        ref="upload"
        class="upload-box"
        drag
        action=""
        :http-request="HttpRequest"
        :auto-upload="false"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        name="files"
        :before-upload="beforeUploadnew"
        :data="uploadlg.extraData"
        :on-change="changeUpload"
        :on-remove="reMoveUpload"
        :on-success="uploadSuccess"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击选择导入文件</em>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-upload2"
          @click="submitFile"
          >导入</el-button
        >
      </span>
    </el-dialog>
    <update-price ref="UpdatePrice" @refreshList="refreshList"></update-price>
    <table-formss ref="viewBtns" @refreshDataList="getList"></table-formss>
  </div>
</template>

<script>
// import { fetchList,getObj, addObj,putObj, delObj,rmEexport,ImportFile} from '@/api/market/contract/person'
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  rmEexport,
  ImportFile
} from '@/api/market/contractSale/person'
import { tableOption } from '@/const/crud/market/contractSale/person'
import TableForm from './CtContractForm'
import TableForms from './CtContractModifys'
import UpdatePrice from './updatePrice'
import { mapGetters } from 'vuex'
import request from '@/router/axios'
import { ExportUrlFile } from '@/api/common'
import TableFormss from '@/views/market/estate/rmproject/RmProjectModify'
export default {
  name: 'contract',
  components: {
    TableForm,
    TableForms,
    TableFormss,
    UpdatePrice
  },
  data() {
    return {
      viewVisibles: false,
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6 //如果没有后面的-8.64e6就是不可以选择今天的
        }
      },
      search: {
        signDate: []
      },
      addOrUpdateVisible: false,
      viewVisible: false,
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      uploadlg: {
        show: false,
        noUploadFile: true
      },
      tableLoading: true,
      tableOption: tableOption,
      contract_ctproject_get: false,
      contract_ctproject_add: false,
      contract_ctproject_edit: false,
      contract_ctproject_del: false,
      contract_ctproject_import: false,
      contract_ctproject_export: false,
      generator_ctcontractchargesummary_get: false,
      activeName: '0',
      tabOptions: [
        {
          label: '未签',
          value: '0'
        },
        {
          label: '已签',
          value: '1'
        },
        {
          label: '即将到期',
          value: '2'
        },
        {
          label: '到期',
          value: '3'
        },
        {
          label: '终止',
          value: '4'
        },
        {
          label: '续签',
          value: '5'
        }
      ]
    }
  },
  filters: {
    getCtContractProject(val, item, index) {
      if (item) {
        let arr = item.split(',')
        return arr[index]
      } else {
        return ''
      }
    }
  },
  created() {
    this.contract_ctproject_get = this.permissions['generator_ctcontract_get']
    this.contract_ctproject_add = this.permissions['generator_ctcontract_add']
    this.contract_ctproject_edit = this.permissions['generator_ctcontract_edit']
    this.contract_ctproject_del = this.permissions['generator_ctcontract_del']
    this.contract_ctproject_export = this.permissions[
      'contract_ctproject_export'
    ]
    this.contract_ctproject_import = this.permissions[
      'contract_ctproject_import'
    ]
    this.generator_ctcontractchargesummary_get = this.permissions[
      'generator_ctcontractchargesummary_get'
    ]
  },
  computed: {
    ...mapGetters(['elements', 'permissions']),
    ComProjectId(val) {
      debugger
      console.log(val)
      if (val) {
        let arr = val.split(',')
        return arr
      } else {
        return []
      }
    }
  },
  methods: {
    handleViewEstate: function (method, id) {
      // this.viewVisibles = true
      // let arr = ids.split(',')
      // let id = null
      // arr.forEach((item, indexs) => {
      //   if (indexs == index) {
      //     id = item
      //   }
      // })
      this.$refs.viewBtns.init(method, id)
    },
    BeforeClose() {
      this.uploadlg.show = false
      this.$refs.upload.clearFiles()
    },
    // 导入成功
    uploadSuccessNew(res) {
      this.getList(this.page)
    },
    refreshList() {
      this.getList(this.page)
    },
    updatePrice(contractId, id) {
      this.$refs.UpdatePrice.init(contractId, id)
    },
    // 切换tab事件
    handleClick(tab, event) {
      this.getList(this.page)
    },
    getList(page, params) {
      //this.tableData =  [{ "id": "14", "contractNumber": "Z20190917001","contractTotalAmount":"12333", "companyName": "重庆市旺源汽车销售有限公司", "projectBuildingId": "1", "createDate": "2018-04-20 07:15:18", "updateDate": "2020-07-14 19:04:15", "contractTypeName": "100", "signDate": "2020-07-14", "projectName": "B1-17-19", "contractStatus": "0", "createBy": "Z20190917001", "updateBy": "Z20190917001" }]
      //this.page.total = 1
      this.searchForm.contractStatus = this.activeName
      this.tableLoading = true
      // if (this.search.signDate.length > 0) {
      //   this.searchForm.signStartDate = this.search.signDate[0]
      //   this.searchForm.signEndDate = this.search.signDate[1]
      // } else {
      //   this.searchForm.signStartDate = ''
      //   this.searchForm.signEndDate = ''
      // }


      this.searchForm.contractTypeId = 1
      fetchList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
          console.log(this.tableData)
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    // 删除
    handleDelete: function (row, index) {
      this.$confirm('是否确认删除此条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return delObj(row.id)
        })
        .then((data) => {
          this.$message.success('删除成功')
          this.getList(this.page)
        })
    },
    // 查看
    handleView: function (method, row) {
      this.viewVisible = true
      this.$nextTick(() => {
        this.$refs.viewBtn.init(method, row.id, row.ctContractProject)
      })
    },
    // 新增、修改
    addOrUpdateHandle(method, id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(method, id)
      })
    },
    // 续签
    openxuqian(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init('continue', id)
      })
    },
    // 导出
    rmEexport() {
      this.tableLoading = true
      this.searchForm.contractStatus = null
      if (this.search.signDate.length > 0) {
        this.searchForm.signStartDate = this.search.signDate[0]
        this.searchForm.signEndDate = this.search.signDate[1]
      } else {
        this.searchForm.signStartDate = ''
        this.searchForm.signEndDate = ''
      }
      rmEexport(this.searchForm).then((response) => {
        if (!response) {
          return
        }
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(new Blob([response.data]))
        link.target = '_blank'
        let filename = response.headers['content-disposition']
        link.download = decodeURI(filename)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.tableLoading = false
      })
    },
    // 导入
    rmImport: function () {
      this.uploadlg.show = true
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    searchChange(form, done) {
      // this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    searchReset() {
      this.search.signDate = []
    },
    refreshChange() {
      this.getList(this.page)
    },
    beforeUpload(file) {
      const isExcel =
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.warning('导入文件格式只能上传.xlsx或.xls!')
      }

      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.warning('上传文件的大小不能超过 50M!')
      }

      return isLt50M && isExcel
    },
    HttpRequest(file) {
      let fromdata = new FormData()
      fromdata.append('file', file.file)
      ImportFile(fromdata).then((res) => {
        this.BeforeClose()
        this.getList(this.page)

      })
    },
    beforeUploadnew(file) {
      const isExcel = file.name.split('.')[file.name.split('.').length - 1]
      if (isExcel === 'xlsx') {
        return true
      } else {
        this.$message.warning(`只能导入后缀为.xlsx的文件`)
        return false
      }
    },
    handleExceed(files) {
      this.$message.warning(`当前导入限制只能上传 1 个文件`)
    },
    uploadSuccess(response) {
      const reSuccess = response.success
      if (reSuccess === 0) {
        if (response.data === null) {
          this.$message({
            type: 'error',
            message: response.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: response.data
              .map((item) => {
                return item.failMsg + '|'
              })
              .join()
          })
        }
        this.$refs.upload && this.$refs.upload.clearFiles()
        return
      }

      this.uploadlg.show = false
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
      this.$refs.upload.clearFiles()
      this.$refs.listTable.initTableData()
    },
    changeUpload(file, fileList) {
      if (fileList.length > 0) {
        this.uploadlg.noUploadFile = false
      } else {
        this.uploadlg.noUploadFile = true
      }
    },
    reMoveUpload(file, fileList) {
      if (fileList.length === 0) {
        this.uploadlg.noUploadFile = true
      }
    },
    submitFile() {
      if (this.uploadlg.noUploadFile) {
        this.$message({
          type: 'warning',
          message: '请选择文件'
        })

        return
      }
      this.$refs.upload.submit()
    },
    //下载文件
    onDowmload() {
      ExportUrlFile('/contract/template/0', {})
      // this.$message({
      //   type: 'success',
      //   message: '开发中!'
      // })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
